<template>
  <div class="warpper-box">
    <div class="inner_box">
      <el-form :inline="true" size="small" :model="formInline" ref="formInline">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="formInline.name" placeholder="公司名称"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="contactPerson">
          <el-input
            v-model="formInline.contactPerson"
            placeholder="姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input
            v-model="formInline.contactPhone"
            placeholder="电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formInline.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="otherRemarks">
          <el-input v-model="formInline.otherRemarks" placeholder="备注"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="loadList(true)">搜索</el-button>
           <el-button type="primary" icon="el-icon-setting" @click="reset('formInline')">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="psm-duo">
         <el-button type="primary" size="small" @click="dataXlsx()">导出EXCEL</el-button>
         <el-button type="danger" size="small" :disabled="selectItem.length == 0" @click="delBatch()">批量删除</el-button>
         <el-button type="danger" size="small" :disabled="selectItem.length == 0" @click="healerMoverBlacklist()">移入黑名单菜单</el-button>
      </div>
      
       <supplier-common-list
       ref="createSupplier"
       :tableData="tables.tableData" 
       :tableLabel="tables.tableLabel"
       :operateWin="180"
       :models="tables" 
       @on-search-click="loadList"
       @on-selection-click="selectionChange"
       @on-detail-click="supplierDetailClick"
       @on-del-click="del"
       @on-remark-click="remarkClick"
       />
    </div>

    <el-dialog :title="tipsForm.title" :visible.sync="tipsForm.visible" width="600px" :close-on-click-modal="false">
       <el-form size="small" :model="tipsForm" label-width="100px" ref="tipsForm">
        <el-form-item label="移入供应商">
          <el-tag v-for="item in selectItem" :key="item.id">{{ item.name }}</el-tag>
        </el-form-item>
        <el-form-item label="移入理由" prop="reason" :rules="[{required: true, message:'请输入移入理由', trigger: 'blur'}]">
          <el-input
            type="textarea"
            :rows="3"
            v-model="tipsForm.reason"
            placeholder="请输入移入理由"
          ></el-input>
        </el-form-item>
       </el-form>
        <div slot="footer" class="dialog-footer">
              <el-button size="small" @click="tipsForm.visible = false">取 消</el-button>
              <el-button size="small" type="primary" @click="submitAddly('tipsForm')">提交</el-button>
          </div>
    </el-dialog>

    <supplierDetail ref="createSupplierDetail" />

  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { supplierPageFind, supplierDelBatch,supplierPause,supplierMoveBlacklist,supplierSignDel,updateStoreRemark } from "@/api/supplier_api";
import { checkEmail, checkPhone } from "@/utils/index";
import { SUPPLIER_POOL_LABEL } from "@/views/supplier/supplierModel/config";
import supplierDetail from '@/views/supplier/supplierModel/supplier_detail.vue'
import supplierCommonList from "@/views/supplier/supplierModel/supplier_common_list.vue"
import moment from "moment";
export default {
  components: {
    supplierDetail,
    supplierCommonList
  },
  data() {
    return {
      formInline: {
        name: "",
        contactPerson: "",
        contactPhone: "",
        statusFlag: "",
        email: "",
        otherRemarks:""
      },
      tables:{
          total:0,
          hackReset:true,
        tableData: [],
          tableLabel:SUPPLIER_POOL_LABEL
      },
        selectItem:[],
      models: {
        pageNum: 1,
        pageSize: 10
      },
      tipsForm: {
        visible: false,
       reason:'',
        callbackType:'',
        title:''
      }
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.loadList(true);
  },
  methods: {
    async loadList(formData) {
      if (typeof formData == 'boolean') {
        this.models.pageNum = 1;
        this.models.pageSize = 10;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (typeof formData == 'object') {
         this.models.pageNum = formData.pageNum;
        this.models.pageSize = formData.pageSize;
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
        }
      }
      if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      let param = {};
      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.otherRemarks = this.formInline.otherRemarks
     // param.statusFlag = this.formInline.statusFlag;
      param.pageNum = this.models.pageNum;
      param.pageSize = this.models.pageSize;
      param.queryType = this.findType["pool"];
      const { code, data } = await supplierPageFind(param);
      if (code == 200) {
          data.list.forEach(v => {
            v.del = true,
            v.setRemark = true
        })
        this.tables.tableData = data.list
        this.tables.total = data.total
      }
    },
    reset(formName){
      this.$refs[formName].resetFields();
      this.loadList(true);
    },
    remarkClick(row) {
      let that = this
       this.$prompt('请输入备注', '备注信息', {
        confirmButtonText: '保存',
           cancelButtonText: '取消',
         inputPlaceholder: '请输入备注信息',
         inputValue: row.otherRemarks,
         closeOnClickModal:false,
          beforeClose: async (action, instance, done) => {
          if (action === 'confirm') {
            const value = instance.inputValue;
            const isValid = this.validateInput(value);
            if (isValid) {
              try {
                row.remarks = value
                const _isValid = await this.mockApiCall(row);
                if (_isValid) {
                  that.loadList();
                  done();
                } 
              } catch (error) {
                this.$message.error('接口请求出错，请稍后重试');
              }
            } else {
              this.$message.error('请输入备注信息');
            }
          } else {
            done();
          }
        },
      }).then(() => {}).catch(() => {});
    },
    mockApiCall(result){
      return new Promise(async (resolve) => {
          const data = await updateStoreRemark(result)
          resolve(data);
      });
    },
    validateInput(value){
      return value.trim()!== '';
    },
    del(row) {
      let name = `确认删除公司名称为【${row.name}】？`;
      let param = {};
      param.id = row.id;
      this.$confirm(name, "温馨提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { code, msg } = await supplierSignDel(param);
          if (code === 200) {
            this.loadList(true);
          }
        })
        .catch(() => {});
    },
    selectionChange(arr){
        this.selectItem = arr;
      },
    delBatch() {
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要删除的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          const ids = this.selectItem.map(v => v.id)
          const {code} = await supplierDelBatch(ids);
          if(code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
    },
     supplierDetailClick(row) {
      this.$refs.createSupplierDetail.openDetail(row,1)
    },
    async dataXlsx() {
      let param = {};
      param.pageNum = 1;
      param.pageSize = this.tables.total;
       if (
        this.formInline.contactPhone &&
        !checkPhone(this.formInline.contactPhone)
      ) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      if (this.formInline.email && !checkEmail(this.formInline.email)) {
        this.$message.error("邮箱输入格式有误");
        return;
      }
      param.contactPhone = this.formInline.contactPhone;
      param.email = this.formInline.email;
      param.contactPerson = this.formInline.contactPerson;
      param.name = this.formInline.name;
      param.otherRemarks = this.formInline.otherRemarks
     // param.statusFlag = this.formInline.statusFlag;
     // param.pageNum = this.models.pageNum;
     // param.pageSize = this.models.pageSize;
      param.queryType = this.findType["pool"];
      const {code,data} = await supplierPageFind(param);
      if (code === 200) {

        let fields = {}
        SUPPLIER_POOL_LABEL.forEach(v => {
        if (v.type == 'on') {
          fields['index'] = v.label
        } else {
          if (v.prop) {
            fields[v.prop] = v.label
          }
        }
        })
        const entries = Object.entries(fields);
        if (entries.length > 0) {
          const firstEntry = entries.shift();
          entries.push(firstEntry);
        }
      const header = Object.fromEntries(entries);
        const manualWidthColumns = [
          { width: 10 },
          { width: 35 },
          { width: 15 },
          { width: 15 },
          { width: 25 },
          { width: 30 },
          { width: 20 },
          { width: 20 },
          { width: 50 }
        ];
        data.list.forEach((v, i) => {
          v.index = (i + 1)
          if (v.createTime) {
            let time = moment(v.createTime).format("YYYY-MM-DD");
            v.createTime = time
          }
          if (v.checkTime) {
            let time = moment(v.checkTime).format("YYYY-MM-DD");
            v.checkTime = time
          }
        })
        
        if (this.$refs.createSupplier) {
          this.$refs.createSupplier.clearSelected()
          this.$refs.createSupplier.exportXlsx(header,data.list,manualWidthColumns,'公共池列表')
        }
      }
    },
    healerMoverBlacklist() {
      this.tipsForm.title = '移入黑名单菜单'
      this.tipsForm.reason = ''
      this.tipsForm.callbackType = 'blacklist'
      this.tipsForm.visible = true
    },
    async callApi(callbackType) {
      let p = 0;
      for (let i = 0; i < this.selectItem.length; i++){
        let item = this.selectItem[i]
        let param = {}
        param.id = item.id
        if (this.tipsForm.callbackType == 'pause') {
          param.pauseReason = this.tipsForm.reason
          param.supplierStoreIds = item.applyCategoryId
        } else {
          param.blacklistReason = this.tipsForm.reason
        }
        const { code } = callbackType == 'pause' ? await supplierPause(param) : await supplierMoveBlacklist(param);
        if (code == 200) {
          p++
        }
      }
      if (p == this.selectItem.length) {
        this.$message.success('移入成功');
        this.tipsForm.visible = false
        this.loadList(true);
      }
    },
    submitAddly(formName) {
       this.$refs[formName].validate(async (valid) => {
         if (valid) {
           this.callApi(this.tipsForm.callbackType)
        }
      });
    }
  }
};
</script>
<style scoped>
.duo-file{
  display: flex;
  flex-wrap: wrap;
}
.psm-duo{
  margin-bottom: 10px;
}
</style>